//
//  XLUserData.m
//  industry
//
//  Created by xl on 2020/11/11.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLUserData.h"
#import "XLUserDefaults.h"
#import "AppStartUpConfig.h"

@interface XLUserData ()

@property (nonatomic, strong) XLUserInfo *currentUserInfo;

@end
@implementation XLUserData
XLShareInstance_implementation(XLUserData)

#pragma mark - Public
- (void)saveCurrentUserInfo:(XLUserInfo *)userInfo {
    if ([NSThread isMainThread] == false) {
        XLLog(@"setting current user from worker thread.");
        WEAKSELF
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf setCurrentUserInfo:userInfo];
        });
        return;
    }
     
     if (userInfo == nil) {
         //退出登录
         [XLUserDefaults saveLastAvailableToken:nil];
         [XLUserDefaults saveCurrentLoginUserJson:nil];
         self.currentUserInfo = nil;
     } else {
         NSData *userData = [userInfo mj_JSONData];
         [XLUserDefaults saveCurrentLoginUserJson:userData];
         self.currentUserInfo = userInfo;
         [AppStartUpConfig sharedAppStartUpConfig].isStaff = userInfo.isStaff;
     }
}

- (XLUserInfo *)getCurrentUserInfo {
    if (self.currentUserInfo != nil) {
        return self.currentUserInfo;
    }
    NSData *userData = [XLUserDefaults getCurrentLoginUserInfoJson];
    if (userData == nil) {
        //从disk获取
        return nil;
    }
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:userData options:0 error:nil];
    self.currentUserInfo = [XLUserInfo mj_objectWithKeyValues:dict];
    return self.currentUserInfo;
}

@end
